import React, { useState, useEffect } from 'react';
import Header from './components/Header';
import Navigation from './components/Navigation';
import EventForm from './components/EventForm';
import EventList from './components/EventList';
import Statistics from './components/Statistics';
import UserProfile from './components/UserProfile';
import Timer from './components/Timer';
import { FishEvent, UserStats, DateFilter } from './types';
import { userLevels } from './data/categories';
import { StorageUtil } from './utils/storage';

type Tab = 'record' | 'stats' | 'timer' | 'profile';

function App() {
  const [activeTab, setActiveTab] = useState<Tab>('record');
  const [events, setEvents] = useState<FishEvent[]>([]);
  const [stats, setStats] = useState<UserStats>({
    totalEvents: 0,
    totalDuration: 0,
    currentLevel: 0,
    levelProgress: 0,
    achievements: []
  });
  const [dateFilter, setDateFilter] = useState<DateFilter>('all');

  // 初始化数据
  useEffect(() => {
    const savedEvents = StorageUtil.getEvents();
    const savedStats = StorageUtil.getStats();
    setEvents(savedEvents);
    setStats(savedStats);
    
    // 如果没有统计数据，基于事件重新计算
    if (savedEvents.length > 0 && savedStats.totalEvents === 0) {
      updateStats(savedEvents);
    }
  }, []);

  // 计算用户等级和进度
  const calculateLevel = (totalEvents: number) => {
    let level = 0;
    for (let i = userLevels.length - 1; i >= 0; i--) {
      if (totalEvents >= userLevels[i].minEvents) {
        level = i;
        break;
      }
    }

    const currentLevelInfo = userLevels[level];
    const nextLevelInfo = userLevels[level + 1];
    
    let progress = 0;
    if (nextLevelInfo) {
      const currentLevelEvents = totalEvents - currentLevelInfo.minEvents;
      const eventsToNext = nextLevelInfo.minEvents - currentLevelInfo.minEvents;
      progress = (currentLevelEvents / eventsToNext) * 100;
    } else {
      progress = 100; // 已达到最高等级
    }

    return { level, progress };
  };

  // 更新统计数据
  const updateStats = (eventList: FishEvent[]) => {
    const totalEvents = eventList.length;
    const totalDuration = eventList.reduce((sum, event) => sum + event.duration, 0);
    const { level, progress } = calculateLevel(totalEvents);

    const newStats: UserStats = {
      totalEvents,
      totalDuration,
      currentLevel: level,
      levelProgress: progress,
      achievements: []
    };

    setStats(newStats);
    StorageUtil.saveStats(newStats);
  };

  // 添加新事件
  const handleEventSaved = (event: FishEvent) => {
    const newEvents = [event, ...events];
    setEvents(newEvents);
    StorageUtil.saveEvents(newEvents);
    updateStats(newEvents);
    
    // 显示成功提示
    if ('Notification' in window && Notification.permission === 'granted') {
      new Notification('摸鱼记录已保存！', {
        body: `成功记录了一次${event.duration}分钟的摸鱼时光 🐟`,
        icon: '/vite.svg'
      });
    }
  };

  // 删除事件
  const handleDeleteEvent = (eventId: string) => {
    const newEvents = events.filter(event => event.id !== eventId);
    setEvents(newEvents);
    StorageUtil.saveEvents(newEvents);
    updateStats(newEvents);
  };

  // 清空所有数据
  const handleClearData = () => {
    if (confirm('确定要清空所有摸鱼记录吗？此操作不可恢复！')) {
      setEvents([]);
      setStats({
        totalEvents: 0,
        totalDuration: 0,
        currentLevel: 0,
        levelProgress: 0,
        achievements: []
      });
      StorageUtil.clearAllData();
    }
  };

  // 导出数据
  const handleExportData = () => {
    const data = {
      events,
      stats,
      exportDate: new Date().toISOString(),
      version: '1.0'
    };
    
    const blob = new Blob([JSON.stringify(data, null, 2)], {
      type: 'application/json'
    });
    
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `摸鱼记录_${new Date().toLocaleDateString('zh-CN')}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  // 导入数据
  const handleImportData = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const data = JSON.parse(e.target?.result as string);
        if (data.events && Array.isArray(data.events)) {
          setEvents(data.events);
          StorageUtil.saveEvents(data.events);
          updateStats(data.events);
          alert('数据导入成功！');
        } else {
          alert('文件格式不正确！');
        }
      } catch (error) {
        alert('文件解析失败！');
      }
    };
    reader.readAsText(file);
    
    // 清空input值，允许重复选择同一文件
    event.target.value = '';
  };

  // 请求通知权限
  useEffect(() => {
    if ('Notification' in window && Notification.permission === 'default') {
      Notification.requestPermission();
    }
  }, []);

  const currentLevelInfo = userLevels[stats.currentLevel] || userLevels[0];

  return (
    <div className="min-h-screen bg-gray-100">
      <div className="max-w-6xl mx-auto p-4">
        <Header
          currentLevel={stats.currentLevel}
          levelTitle={currentLevelInfo.title}
          levelProgress={stats.levelProgress}
          totalEvents={stats.totalEvents}
        />
        
        <Navigation
          activeTab={activeTab}
          onTabChange={setActiveTab}
        />

        <main>
          {activeTab === 'record' && (
            <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
              <EventForm onEventSaved={handleEventSaved} />
              <EventList
                events={events}
                dateFilter={dateFilter}
                onDateFilterChange={setDateFilter}
                onDeleteEvent={handleDeleteEvent}
              />
            </div>
          )}

          {activeTab === 'stats' && (
            <Statistics
              events={events}
              dateFilter={dateFilter}
              onDateFilterChange={setDateFilter}
            />
          )}

          {activeTab === 'timer' && (
            <Timer onEventSaved={handleEventSaved} />
          )}

          {activeTab === 'profile' && (
            <UserProfile
              stats={stats}
              onClearData={handleClearData}
              onExportData={handleExportData}
              onImportData={handleImportData}
            />
          )}
        </main>

        {/* 页脚 */}
        <footer className="text-center text-gray-500 text-sm mt-8 pb-4">
          <p>摸鱼管理系统 v1.0 | 合理摸鱼，快乐工作 🐟</p>
        </footer>
      </div>
    </div>
  );
}

export default App;